# coding=utf-8

import json
import datetime

from django.db import models
from django.utils import timezone
from django.conf import settings

from utils.format import strftime, strfdate

from apps.tenant.models import Tenant

class BizLogManager(models.Manager):
    def addnew(self, tenant, user, type, description, data=None):
        def default(o):
            if isinstance(o, datetime.datetime):
                return strftime(o)
            elif isinstance(o, datetime.date):
                return strfdate(o)

        row = self.model(tenant=tenant, user=user, type=type, description=description)
        if data:
            row.data = json.dumps(data, default=default)
        row.save()
        return row

class BizLog(models.Model):
    INSERT = 1
    UPDATE = 2
    DELETE = 3
    TYPE_CHOICES = (
        (INSERT, u'添加'),
        (UPDATE, u'修改'),
        (DELETE, u'删除'),
    )
    TYPE_JSON = [{'id': item[0], 'value': item[1]} for item in TYPE_CHOICES]

    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, null=True, blank=True)
    type = models.PositiveSmallIntegerField(choices=TYPE_CHOICES, verbose_name=u"类别")
    description = models.CharField(max_length=1000, verbose_name=u"内容")
    data = models.TextField(verbose_name=u"数据", null=True, blank=True)
    create_time = models.DateTimeField(verbose_name=u"添加时间", default=timezone.now, editable=False)
    tenant = models.ForeignKey(Tenant,verbose_name=u'租户',on_delete=models.PROTECT,null=True, blank=True)

    objects = BizLogManager()

    class Meta:
        db_table = "system_log"
        ordering = ['-id']
        index_together = (
            'create_time',
            'type',
        )
        verbose_name = u"系统日志"
        default_permissions = ()
